import {
  Body,
  Controller,
  Post, Req,
  UploadedFile, UploadedFiles,
  UseInterceptors
} from "@nestjs/common";
import { AnyFilesInterceptor, FileInterceptor } from "@nestjs/platform-express";
import { QiniuService } from './qiniu.service';
import { diskStorage } from 'multer';
import * as fs from 'fs';
import * as path from 'path';
import * as Busboy from 'busboy';
import { Public } from '../../global/decorator/public.decorator';

@Controller('qiniu')
export class QiniuController {
  constructor(private readonly qiniuService: QiniuService) {}

  @Public()
  @Post('demo')
  @UseInterceptors(AnyFilesInterceptor())
  async handleUpload(
    @UploadedFiles() files: Array<Express.Multer.File>,
    @Body() body: any,
  ) {
    const fileInfo = files.map((file) => ({
      fieldname: file.fieldname,
      originalname: file.originalname,
      mimetype: file.mimetype, // ✅ 这里获取文件类型
      size: file.size,
    }));

    console.log('接收到字段:', body);
    console.log('接收到文件信息:', fileInfo);

    return {
      files: fileInfo,
    };
  }

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, cb) => {
          const filename = `${Date.now()}-${file.originalname}`;
          cb(null, filename);
        },
      }),
    }),
  )
  async upload(@UploadedFile() file: any) {
    console.log(file);
    const filePath = file.path;
    console.log(filePath);
    const key = `uploads/${file.filename}`; // 七牛上的文件路径
    try {
      const url = await this.qiniuService.uploadFile(filePath, key);
      fs.unlinkSync(filePath); // 删除本地文件
      return url;
    } catch (err) {
      console.log(err);
      fs.existsSync(filePath) && fs.unlinkSync(filePath);
      return { error: '上传失败', detail: err };
    }
  }
}
